import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { DbService } from 'src/db/db.service';
import { User } from './entities/user.entity';
import { LoginUserDto } from './dto/login-user.dto';

@Injectable()
export class UserService {
  @Inject()
  private readonly dbService: DbService;

  async create(createUserDto: CreateUserDto) {
    const users: User[] = await this.dbService.read();
    const foundUser = users.find((item) => item.username === createUserDto.username);
    // 1 校验用户名唯一
    if (foundUser) throw new BadRequestException('用户已存在');
    // 2 保存用户
    const user = new User();
    user.id = users.length + 1;
    user.username = createUserDto.username;
    user.password = createUserDto.password;
    users.push(user);
    // 3 写入 JSON 文件
    await this.dbService.write(users);
    // 4 返回用户信息
    return user;
  }

  async login(loginUserDto: LoginUserDto) {
    const users: User[] = await this.dbService.read();
    const foundUser = users.find((item) => item.username === loginUserDto.username);
    if (!foundUser) throw new BadRequestException('用户不存在');
    if (foundUser.password !== loginUserDto.password) throw new BadRequestException('密码错误');
    return foundUser;
  }

  findAll() {
    return `This action returns all user`;
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
